package cn.paranoid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

public class Shiro {
    @Test
    public void shiroLogin(){
        //导入权限ini文件构建权限工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //工厂构建安全管理器  得到SecurityManager实例
        SecurityManager securityManager = factory.getInstance();
        //使用SecurityUtils工具生效安全管理器   并绑定给SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        //使用SecurityUtils工具获得主体
        Subject subject = SecurityUtils.getSubject();
        //构建账号token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("jay","123");
        //登录操作
        try {

            //登陆成功
            subject.login(usernamePasswordToken);
            System.out.println("认证状态：" + subject.isAuthenticated());
            System.out.println("登录成功");
        }catch (UnknownAccountException e){
            //登录失败
            System.out.println("用户名不存在");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }catch (Exception e){
            e.printStackTrace();
        }


        System.out.println(subject.isAuthenticated());
    }
}
